package com.smcaiot.filesync.starter.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Objects;

@Slf4j
public class FileUtils {

    public static String fileNameWithTime(String fileName) {
        if (StrUtil.isBlank(fileName)) {
            return fileName;
        }

        StringBuilder sb = new StringBuilder();
        long time = System.currentTimeMillis();
        int index = fileName.indexOf(".");
        if (index != -1) {
            return sb.append(fileName.substring(0, index))
                    .append(StrUtil.UNDERLINE)
                    .append(time + RandomUtil.randomString(4))
                    .append(fileName.substring(index, fileName.length()))
                    .toString();
        }

        return sb.append(fileName)
                .append(StrUtil.UNDERLINE)
                .append(time + RandomUtil.randomString(4))
                .toString();
    }

    public static InputStream baseToInputStream(String base64) {
        ByteArrayInputStream stream = null;
        try {
            //byte[] bytes = Base64.decodeBase64(base64);
            byte[] bytes = Base64Decoder.decode(base64);
            stream = new ByteArrayInputStream(bytes);
        } catch (Exception e) {
            log.warn("[base64转文件读取流失败], error = {}", e.getMessage());
        }
        return stream;
    }

    public static String getRootByPath(String path) {
        if (StrUtil.isBlank(path)) {
            return null;
        }
        String[] dirs = path.split(StrUtil.SLASH);
        if (Objects.isNull(dirs) || dirs.length == 0) {
            return null;
        }
        for (String d : dirs) {
            if (StrUtil.isNotBlank(d)) {
                return d;
            }
        }
        return null;
    }

    public static String exceptRootByPath(String path) {
        String bucketName = getRootByPath(path);
        if (StrUtil.isBlank(bucketName)) {
            return null;
        }
        if (path.startsWith(StrUtil.SLASH)) {
            path = path.substring(1);
        }
        return path.replaceFirst(bucketName, "");
    }

}
